import React,{useState,useEffect} from 'react'
import { Cascader } from 'antd';
import {post} from '../../Utils/axios'
import {Url} from '@/Utils/services/url'
import { ConsoleSqlOutlined } from '@ant-design/icons';
export default function division(props:any) {
    const [options, setOptions] = useState([]);
    const [cityList,setCityList] = useState([])
    const url = Url.addressList
    useEffect(()=>{
        searchFirstAddress()
        if(props.value && props.value.length == 2){
            setCityList(props.value)
        }
    },[])
    // useEffect(()=>{
        
    //     if(props.value && props.value.length == 2){
    //         setCityList(props.value)
    //     }
    // },[props])
    // useEffect(()=>{
    //     console.log(options)
    //     if(options.length > 0 && cityList.length > 0){
    //         setCityList(props.value)
    //     }
    // },[options])
    function searchFirstAddress(){
        post(url,{addressLevel: 1  }).then(res =>{
            let arr:any = []
            for(let item in res){
                let obj = {
                    ...res[item],
                    value:res[item].addressCode,
                    label:res[item].addressName,
                    isLeaf: false
                }
                arr.push(obj)
            }
            setOptions(arr)
        })
    }
    function searchSecondAdd(selectedOptions:any){
        let obj = {
            addressLevel:2,
            parentId:typeof selectedOptions == 'object'?selectedOptions[0].addressCode:selectedOptions
        }
       
        post(url,{...obj}).then(res =>{
            const targetOption = {
                ...selectedOptions[0],
                children:[],
                loading:true
            }
            for(let item in res){
                let obj = {
                    ...res[item],
                    value:res[item].addressCode,
                    label:res[item].addressName
                }
                targetOption.children.push(obj)
            }
            let arr:any = [...options]
            for(let item in arr){
                if(arr[item].id == targetOption.id){
                    arr[item] = {
                        ...targetOption
                    }
                }
            }
            targetOption.loading = false
            setOptions(arr)
        })
    }
    function onChange(value:any, selectedOptions:any){
        props.normFile(value)
        return value
      };
    return (
      <div>
          <Cascader 
                value={cityList}
                options={options}
                loadData={searchSecondAdd}
                onChange={onChange} 
                changeOnSelect 
            />
      </div>
    )
  }
